<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ include file="/wesite/view/common/base.jsp" %>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>购物车</title>
    <%@ include file="/wesite/view/common/common.jsp" %>
</head>
<body>
<c:if test="${not empty coupons}">
<article class="hig article-text">
    <section class="top-msg">
        <span class="fl">您有 <en> ${fn:length(coupons)}</en> 张优惠券可领取</span>
        <a class="give-btn fr" href="javascript:;">点击领取</a>
        <a class="close-btn" href="javascript:;"></a>
    </section>
</article>
</c:if>
<div class="shopping-cart marketing-cart">
    <div class="shopping-cart-null" style="display: none;">
        <span class="txt-kong-img"><img src="${webctx}/images/Thome.png"></span>
        <p style="font-size: 18px; margin-top: 15px">购物车还是空的，赶快去添加商品吧~</p>
    </div>
</div>
<div class="mask"></div>
<%request.setAttribute("bottomMenuId", "shopping");%>
<%@ include file="/wesite/view/common/bottom.jsp" %>
<%@ include file="/wesite/view/common/coupon-popup.jsp"%>
</body>
<script src="${webctx}/script/aui-toast.js"></script>
<script src="${webctx}/script/aui-dialog.js"></script>
<script src="${ctx }/plugins/artTemplate/dist/template.js"></script>
<script type="text/javascript">

    $(".give-btn").click(function () {
        $(".mask").fadeIn("slow");//遮罩层
        $(".coupon-popup-in").fadeIn("slow");
    });
    $(".close").click(function () {
        $(".mask").fadeOut("slow"); //遮罩层
        $(".coupon-popup-in").fadeOut("slow");
    });
    $(".mask").click(function () {
        $(".mask").fadeOut("slow"); //遮罩层
        $(".coupon-popup-in").fadeOut("slow");
    });
    $(".close-btn").click(function () {
        $(".article-text").fadeOut("slow");
    })

    var toast = new auiToast({});
    function showToastLoading(msg) {
        toast.loading({
            title: msg
        });
    }

    function hideToastLoading() {
        toast.hide();
    }

    //添加遮罩
    function showhisp() {
        $(".order-content").each(function () {
            var canbuy = $(this).find(".canbuy").val();
            var statusck = $(this).find(".statusck").val();
            var amount = $(this).find(".amount").val();
            if (canbuy == 1) {
                if (canbuy == 1 && statusck == 2) {
                    if (amount <= 0) {
                        $(this).find(".mask-sm").removeClass("productbox").css("display", "block").text("无货");
                    }
                } else if (statusck != 2) {
                    $(this).find(".mask-sm").css("display", "block").text("已下架");
                }
            } else {
                $(this).find(".mask-sm").css("display", "block");
            }
        })
    }
    function checkbox(obj, ischeck) {
        if (ischeck) {
            if (obj.get(0).className.indexOf("checked") == -1) {
                obj.addClass("checked");
            }
        } else obj.removeClass("checked");
        $("[name='cartcheckbox']", obj).get(0).checked = ischeck;
    }

    function computenum() {
        var count = 0;
        $(".productbox.checked").map(function () {
            count++;
        });
        $(".allbox").each(function () {
            checkbox($(this), count == parseInt($("[name='count']").val()));
        });
        $("#sumnum").text(count);
    }
    $(".shopping-cart").on("click", "#allckb", function () {
        var ischeck = true;
        if ($(this).parents(".allbox").hasClass("checked")) {
            ischeck = false;
            $("#sumnum").text(0);
        } else {
            $("#sumnum").text($("[name='count']").val());
        }
        if(ischeck){
            window.location.href=ctx+'/we/weshopcart';
        }
        selall(ischeck);
        $w.httpRequest({
            url: "${ctx}/we/order/toggleAll",
            data: {"price": $("[name='allTotalPrice']").val(), "flag": ischeck},
            ok: function (ret) {
                $("#heji").text(ret.Data);
                $("input[id^='cartprice']").val(0);
            }
        })
    });
    function selall(ischeck) {
        $(".allbox").each(function () {
            checkbox($(this), ischeck);
        })
        $(".productbox").each(function () {
            checkbox($(this), ischeck);
        })
    }
    function toggleChecked(type, id, cid, pid, obj) {
        var n = $(obj).parents("li").find(".focus-auto-select").val();
        var price = $("#cartprice" + cid).val();
        if (id) {
            price = $("#cartprice" + id).val();
        }
        if ($(obj).hasClass("checked")) {
            checkbox($(obj), false);
            synToggle(type, id, cid, pid, n, price, false);
        } else {
            checkbox($(obj), true);
            synToggle(type, id, cid, pid, n, price, true);
        }
        computenum();
    }
    function synToggle(type, id, cid, pid, count, price, flag) {
        toggleCartItems(type, id, cid, pid, count, price, flag);
    }
    var cart_toggle = false;
    function toggleCartItems(type, id, cid, pid, count, price, flag) {
        if (cart_toggle) {
            return false;
        }
        cart_toggle = true;
        $.ajax({
            type: "get",
            url: "${ctx}/we/order/toggleCart",
            data: {
                "promotionType": type,
                "promotionId": id,
                "id": cid,
                "productid": pid,
                "count": count,
                "price": price,
                "check": flag
            },
            dataType: "json",
            success: function (ret) {
                var data = ret.Data;
                we_splice(data);
                $("#heji").text(data.price);
            },
            complete: function () {
                cart_toggle = false;
            }
        })
    }
    $(".shopping-cart").on("focus", "[name='buynumInp']", function () {
        this.select();
    });
    function we_lessenamount(type, id, cid, pid, obj) {
        var txt = $("[name='buynumInp']", $(obj).parent());
        var n = parseInt(txt.val());
        n--;
        txt.val(n);
        we_inputAmount(type, id, cid, pid, txt);
    }
    function we_addamount(type, id, cid, pid, obj) {
        var txt = $("[name='buynumInp']", $(obj).parent());
        var n = parseInt(txt.val());
        n++;
        txt.val(n);
        we_inputAmount(type, id, cid, pid, txt);
    }
    function we_inputAmount(type, id, cid, pid, obj) {
        $(obj).val($(obj).val().replace(/[^0-9]/g, ''));
        if ($(obj).val() == '0' || $(obj).val() == '') $(obj).val('1');
        if ($(obj).attr("maxnum") && $(obj).val()) {
            var max = parseInt($(obj).attr("maxnum"));
            max = max > 0 ? max : 0;
            if (parseInt($(obj).val()) > max) $(obj).val(max);
        }
        if ($(obj).parents("li").find(".productbox").hasClass("checked")) {
            var price = $("#cartprice" + cid).val();
            if (id) {
                price = $("#cartprice" + id).val();
            }
            synBuyCount(type, id, cid, pid, $(obj).val(), price, true);
        }
    }
    var synBuyCountCache = {};
    var synBuyCountTimer = {};
    function synBuyCount(type, id, cid, pid, count, price, flag) {
        var buycount = count + '';
        var buycountCache = synBuyCountCache[pid + ''] + '';
        if (buycount == buycountCache) {
            return true;
        } else {
            synBuyCountCache[pid + ''] = buycount;
            var synBuyCountTimerPre = synBuyCountTimer[pid + ''];
            if (synBuyCountTimerPre > 0) {
                window.clearTimeout(synBuyCountTimerPre);
                synBuyCountTimer[pid + ''] = -1;
            }
            var synBuyCountTimerTemp = window.setTimeout(function () {
                synBuyCountTimer[pid + ''] = -1;
                synCartItems(type, id, cid, pid, count, price, flag);
            }, 600);
            synBuyCountTimer[pid + ''] = synBuyCountTimerTemp;
        }
    }
    var submit = false;
    function synCartItems(type, id, cid, pid, count, price, flag) {
        if (submit)return;
        submit = true;
        $w.httpRequest({
            url: "${ctx}/we/order/syncart",
            data: {
                "promotionType": type,
                "promotionId": id,
                "id": cid,
                "productid": pid,
                "count": count,
                "price": price,
                "check": flag
            },
            ok: function (ret) {
                var data = ret.Data;
                we_splice(data);
                $("#heji").text(data.price);
            },
            all: function () {
                submit = false;
            }
        })
    }
    function we_splice(data) {
        var type = data.type;
        var data = data.data;
        switch (type) {
            case 'list':
                var product = data.products[0];
                $("#cart" + product.cartId).html(showComplexItem(type, product));
                break;
            case 'complex':
                var products = data.products;
                for (var j = 0; j < products.length; j++) {
                    var product = products[j];
                    if (product.giftType == '') {
                        $("#cart" + product.cartId).html(showComplexItem(type, product));
                    }
                }
                break;
            case 'purchase_gift':
                $("#cart" + data.promotionId).html(showPurchaseGiftItem(data));
                break;
            case 'money_off':
                $("#cart" + data.promotionId).html(showMoneyOffItem(data));
                break;
        }
    }
    var submiting = false;
    function tojies() {
        var items = [];
        $(".productbox.checked").each(function () {
            var item = {};
            var cart = $(this).parents("li").find(".focus-auto-select");
            item["id"] = $("[name='cartcheckbox']", $(this)).val();
            item["productid"] = cart.attr("id");
            item["count"] = cart.val();
            items.push(item);
        });
        if (items.length <= 0) {
            toast.fail({
                title: "请选择商品",
                duration: 1000
            })
            return;
        }
        showToastLoading("正在验证...");

        $w.checkAuth("${ctx}/we/weshopcart", function () {
            hideToastLoading();

            if (submiting)return;
            submiting = true;

//            showToastLoading("生成订单...");
            $.ajax({
                url: "${ctx}/we/order/generateorder",
                type: "POST",
                dataType: "json",
                contentType: 'application/json;charset=utf-8',
                data: JSON.stringify(items),
                success: function (ret) {
                    var data = ret.Data;
                    if (ret.MsgCode == '-1') {
                        window.location.href = "${ctx}/we/user/showlogin";
                    } else if (ret.MsgCode == '1') {
                        $("#but").attr("href", "javascript:void(0);");
                        setTimeout('$("#but").attr("href","javascript:tojies()")', 2000);
                        window.location.href = ctx + "/we/order/" + data.orderCode;
                    } else if (ret.MsgCode == '101') {
                        var h = "以下商品库存不足：";
                        var list = window.eval(ret.MsgDesc);
                        for (var i = 0; i < list.length; i++) {
                            var name = list[i].name ? list[i].name : list[i].productname;
                            h += "\r\n" + (i + 1) + "、" + name;
                        }
                        toast.fail({
                            title: h,
                            duration: 1000
                        })
                    } else if (ret.MsgCode == '4011') {
                        var h = "商品";
                        var list = window.eval(ret.MsgDesc);
                        for (var i = 0; i < list.length; i++) {
                            var name = list[i].name ? list[i].name : list[i].productname;
                            h += "【" + name + "】";
                        }
                        h += "超出限购";
                        toast.fail({
                            title: h,
                            duration: 1000
                        })
                    } else if (ret.MsgCode == '102') {
                        var h = "以下商品已下架：";
                        var list = window.eval(ret.MsgDesc);
                        for (var i = 0; i < list.length; i++) {
                            var name = list[i].name ? list[i].name : list[i].productname;
                            h += "\r\n" + (i + 1) + "、" + name;
                        }
                        toast.fail({
                            title: h,
                            duration: 1000
                        })
                    } else if (ret.MsgCode == '103') {
                        var h = "以下商品已不在您的可购范围：";
                        var list = window.eval(ret.MsgDesc);
                        for (var i = 0; i < list.length; i++) {
                            var name = list[i].name ? list[i].name : list[i].productname;
                            h += "\r\n" + (i + 1) + "、" + name;
                        }
                        toast.fail({
                            title: h,
                            duration: 1000
                        })
                    } else {
                        toast.fail({
                            title: ret.MsgDesc,
                            duration: 1000
                        })
                    }
                },
                error: function (ret) {
                    window.location.href = "${ctx}/we/message";
                },
                complete: function () {
                    submiting = false;
                }
            })
        })
    }
    function delCart() {
        var chk_value = [];
        var dialog = new auiDialog({})
        dialog.alert({
            title: "弹出提示",
            msg: '确定删除',
            buttons: ['取消', '确定'],
        }, function (ret) {
            if (ret) {
                if (ret.buttonIndex == 1) {

                }
                if (ret.buttonIndex == 2) {
                    chk_value = $(".productbox.checked").map(function () {
                        return $("[name='cartcheckbox']", $(this)).val();
                    }).get();
                    if (chk_value.length > 0) {
                        $w.httpRequest({
                            url: "${ctx}/we/wedelCartAll",
                            data: {"ids": chk_value},
                            ok: function (ret) {
                                window.location.replace("${ctx}/we/weshopcart");
                            }
                        })
                    } else {
                        dialog.alert({
                            title: "提示",
                            msg: '请选择商品',
                            buttons: ['确定']
                        })
                    }
                }
            }
        });
    }
    function showGiftProduct(product) {
        return template('productHtml_cart_gift', {
            ctx: ctx,
            fileserver: getRandomFileserver(),
            isuserauth: isuserauth,
            islogin: islogin,
            value: product
        });
    }
    function showActiveProduct(type, product, promotionId) {
        return template('productHtml_cart_product', {
            ctx: ctx,
            fileserver: getRandomFileserver(),
            isuserauth: isuserauth,
            islogin: islogin,
            value: product,
            type: type,
            promotionId: promotionId
        });
    }
    function showActiveItem(type, item) {
        var h = "";
        var products = item.products;
        for (var j = 0; j < products.length; j++) {
            var product = products[j];
            if (product.gift) {
                h += showGiftProduct(product);
            } else if (product.giftType == '') {
                h += showActiveProduct(type, product, item.promotionId);
            }
        }
        return h;
    }
    function showPurchaseGiftItem(item) {
        var h = '<div class="active-title"><input type="hidden" id="cartprice' + item.promotionId + '" value="' + item.totalPrice + '"><span>满赠</span>';
        if (item.hasStandard) {
            if (item.standardMoney) {
                h += '活动已购满' + item.standardMoney + '元，已获得赠品<em>&nbsp;' + item.number + '&nbsp;</em>件';
            } else {
                h += '活动已购满' + item.standardAmount + '件，已获得赠品<em>&nbsp;' + item.number + '&nbsp;</em>件';
            }
        } else {
            if (item.standardMoney) {
                h += '活动购满' + item.standardMoney + '元，可获得赠品<em>&nbsp;' + item.number + '&nbsp;</em>件';
            } else {
                h += '活动购满' + item.standardAmount + '件，可获得赠品<em>&nbsp;' + item.number + '&nbsp;</em>件';
            }
        }
        h += '</div><ul>';
        h += showActiveItem("purchase_gift", item);
        h += "</ul>";
        return h;
    }
    function showPurchaseGiftProducts(items) {
        var h = "";
        if (items) {
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                h += '<div class="order-content order-cont-active" id="cart' + item.promotionId + '">';
                h += showPurchaseGiftItem(item);
                h += '</div>';
            }
        }
        return h;
    }
    function showMoneyOffItem(item) {
        var h = '<div class="active-title"><input type="hidden" id="cartprice' + item.promotionId + '" value="' + item.totalPrice + '"><span>满减</span>';
        if (item.available) {
            h += " 活动已购满" + item.standardMoney;
            if (item.discountRate > 0) {
                h += ',已打<em>' + item.discountRate + '</em>折';
            } else {
                h += ',已减<em>' + item.discountMoney + '</em>元';
            }
        } else {
            h += "活动";
            var rules = item.items;
            for (var i = 0; i < rules.length; i++) {
                var rule = rules[i];
                h += "满" + rule.offMoney + "元";
                if (rule.discountRate > 0) {
                    h += '打' + rule.discountRate + '折,';
                } else {
                    h += '减' + rule.discountMoney + ',';
                }
            }
        }
        h += '</div><ul>';
        h += showActiveItem("money_off", item);
        h += "</ul>";
        return h;
    }
    function showMoneyOffProducts(items) {
        var h = "";
        if (items) {
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                h += '<div class="order-content order-cont-active" id="cart' + item.promotionId + '">';
                h += showMoneyOffItem(item);
                h += '</div>';
            }
        }
        return h;
    }
    function showComplexItem(type, product) {
        var h = '<ul><input type="hidden" id="cartprice' + product.cartId + '" value="' + product.totalPrice + '">';
        h += showActiveProduct(type, product, "");
        h += '</ul>';
        return h;
    }
    function showComplexProducts(type, products) {
        var h = "";
        if (products) {
            for (var j = 0; j < products.length; j++) {
                var product = products[j];
                if (product.giftType == '') {
                    h += '<div class="order-content" id="cart' + product.cartId + '">';
                    h += showComplexItem(type, product);
                    h += '</div>';
                }
            }
        }
        return h;
    }
    $(function () {
        showhisp();
        $w.httpRequest({
            method: "get",
            url: ctx + "/we/order/cart",
            ok: function (ret) {
                var data = ret.Data;
                if (data.count > 0) {
                    var itemHtml = '<input type="hidden" name="count" value="' + data.count + '"><div class="hd"><div class="fl"><span >共：<i id="sumAll">' + data.count + '</i>件商品</span><span>已选<i id="sumnum">' + data.count + '</i>件</span></div>'
                        + '<div class="fr allbox checked"><span><input id="allckb" type="checkbox" name="cartcheckbox" checked="checked"/><span class="chk-ico"></span> 全选</span><span onclick="delCart()">删除</span></div></div>';
                    itemHtml += showComplexProducts("list", data.list);
                    itemHtml += showComplexProducts("complex", data.complex);
                    itemHtml += showMoneyOffProducts(data.money_off);
                    itemHtml += showPurchaseGiftProducts(data.purchase_gift);
                    itemHtml += '<div class="h98"></div><div class="shopping-cart-bottom"><div class="fl"><p><div class="ft-inner">合计：<span name="heji" id="heji">' + data.totalPrice + '</span> 元</div></p></div>'
                        + '<div class="btn fr" ><a href="javascript:tojies()" id="but"><span >结算</span></a></div></div><input type="hidden" name="allTotalPrice" value="' + data.totalPrice + '">';
                    $(".shopping-cart").html(itemHtml);
                } else {
                    $(".shopping-cart-null").show();
                }
            }
        })
    })
</script>
<script type="text/html" id="productHtml_cart_product">
    <li>
        <div>
            <div class="selectbox productbox {{value.check?'checked':''}}"
                 onclick="toggleChecked('{{type}}','{{promotionId}}','{{value.cartId }}','{{value.id}}',this);">
                <input class="clck" name="cartcheckbox" type="checkbox" value="{{value.cartId}}" {{value.check?'checked="checked"':''}}/>
                <label class="J_select">
                </label>
            </div>
            <div class="img">
                <div class="mask-sm"></div>
                <div class="td-inner">
                    <a href="/we/product/{{value.id}}" ><img
                            src="{{fileserver}}{{value.photo}}" width="90" height="90" alt=""
                            onerror="this.src='{{ctx}}/wesite/images/noimg.jpg'"></a>
                </div>
            </div>
            <div class="con">
                <h3>{{value.name}}</h3>
                <div class="data">
                    <p>厂家：{{value.b_chanjia}}</p>
                    <p>规格：{{value.b_guige}}</p>
                    <span class="price">￥<i>{{value.price}}</i></span>
                    <div class="count-box">
                        <i class="sy_minus"
                           onclick="we_lessenamount('{{type}}','{{promotionId}}', '{{value.cartId}}', '{{value.id}}', this);">-</i>
                        <input id="{{value.id}}" name="buynumInp" type="number" class="num focus-auto-select"
                               value="{{value.buyNum}}"
                               onchange="we_inputAmount('{{type}}','{{promotionId}}', '{{value.cartId}}', '{{value.id}}', this);"
                               maxnum="{{value.amount}}">
                        <i class="sy_plus"
                           onclick="we_addamount('{{type}}','{{promotionId}}', '{{value.cartId}}', '{{value.id}}', this);">+</i>
                    </div>
                </div>
                <div class="cl"></div>
            </div>
            <div class="cl"></div>
        </div>
        <!-- 一起存在和一起不存在 -->
        {{if value.buySend}}
        <%--<div class="after-box"></div>--%>
        {{if value.available}}
        <div class="give-buy">买送：{{value.name}} {{value.b_guige}} ×{{value.giftNum}}</div>
        {{else}}
        <div class="give-buy">买{{value.standardNum}}送{{value.sendNum}}</div>
        {{/if}}
        {{/if}}
    </li>
</script>
<script type="text/html" id="productHtml_cart_gift">
    <li>
        <div>
            <!-- 灰色方块 -->
            <div class="grad-el"></div>
            <div class="img">
                <div class="mask-sm"></div>
                <div class="td-inner">
                    <a href="/we/product/{{value.id}}" ><img
                            src="{{fileserver}}{{value.photo}}" width="90" height="90" alt=""
                            onerror="this.src='{{ctx}}/wesite/images/noimg.jpg'"></a>
                </div>
            </div>
            <div class="con">
                <h3><span>赠品</span>{{value.name}}</h3>
                <div class="data">
                    <p>厂家：{{value.b_chanjia==''?'无':value.b_chanjia}}</p>
                    <p>规格：{{value.b_guige}}</p>
                    <div class="td-inner" style="display: none">
                        <strong>¥0.00</strong>
                    </div>
                    <span class="price">￥<i>0.00</i></span>
                    <span class="num">{{value.buyNum}}</span>
                </div>
                <div class="cl"></div>
            </div>
        </div>
    </li>
</script>
</html>